package com.laoxu.java.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.laoxu.java.common.Result;
import com.laoxu.java.common.ResultUtil;
import com.laoxu.java.entity.User;
import com.laoxu.java.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/api")
public class LoginController {

    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public Result<String> login(@RequestBody User user, HttpSession session){
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("username",user.getUsername());
        wrapper.eq("password",user.getPassword());
        User entity = userService.getOne(wrapper);

        if (entity == null){
            return ResultUtil.fail("用户名密码错误！");
        }
        else {
            session.setAttribute("user",entity);
            return ResultUtil.ok("eyJ1aWQiOjUwMCwicmlkIjowLCJpYXQiOjE2MTAzNDg3MjYsImV4cCI6MTYxMDQzNTEyNn0");
        }
    }

    @GetMapping("logout")
    public Result<String> logout(HttpServletRequest request){
        request.getSession().removeAttribute("user");
        return ResultUtil.ok("注销成功");
    }
}
